package com.morn.fanfou;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.morn.fanfou.api.Fanfou;
import com.morn.fanfou.model.Status;
import com.morn.fanfou.widget.PullToRefreshListView;
import com.morn.fanfou.widget.PullToRefreshListView.OnRefreshListener;
import com.morn.fanfou.widget.StatusAdapter;

public class SearchListActivity extends Activity implements OnClickListener, OnItemClickListener {

	private EditText editText;
	private PullToRefreshListView listView;
	private List<Status> statusList = new ArrayList<Status>();
	private View foot;
	private BaseAdapter adapter;
	private ProgressBar footProgressBar;
	private Fanfou fanfou;
	private boolean flag = true;
	private String query;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_list);
		fanfou = ((FanfouApplication) getApplication()).getFanfou();
		findView();
		listView.prepareForRefresh();
		handleIntent(getIntent());
	}

	private void findView() {
		editText = (EditText) findViewById(R.id.searchListEditText);
		listView = (PullToRefreshListView) findViewById(R.id.searchListView);
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setOnItemClickListener(this);
		listView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if (flag)
					new GetStatusTask().execute();

			}
		});
		foot = LayoutInflater.from(this).inflate(R.layout.listview_foot, null);
		foot.setOnClickListener(this);
		footProgressBar = (ProgressBar) foot.findViewById(R.id.listViewFootProgressBar);
		adapter = new StatusAdapter(this, statusList);
		listView.setAdapter(adapter);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		handleIntent(intent);
	}

	public void searchClick(View v) {
		onSearchRequested();
	}

	@Override
	public boolean onSearchRequested() {
		String str = editText.getText().toString();
		startSearch(str, false, null, false);
		return true;
	}

	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			query = intent.getStringExtra(SearchManager.QUERY);
			editText.setText(query);
			listView.onRefresh();
		} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			Uri uri = intent.getData();
			query = uri.getAuthority();
			editText.setText(query);
			listView.onRefresh();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position != 0 || position != adapter.getCount()) {
			Status status = statusList.get(position - 1);
			Intent intent = new Intent(this, StatusViewActivity.class);
			intent.putExtra("status", status);
			this.startActivity(intent);
		}
	}

	@Override
	public void onClick(View v) {
		if (flag) {
			if (v == foot) {
				if (statusList.size() > 0) {
					String maxId = statusList.get(statusList.size() - 1).getId();
					new GetStatusTask().execute(maxId);
				}
			}
		}
	}

	private class GetStatusTask extends AsyncTask<Object, Object, String> {

		private String maxId = null;
		private List<com.morn.fanfou.model.Status> list = null;

		@Override
		protected void onPreExecute() {
			flag = false;
			footProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Object... params) {
			if (params != null && params.length > 0) {
				maxId = (String) params[0];
			}
			String error = "OK";
			try {
				if (query != null && !"".equals(query)) {
					list = fanfou.searchStatus(query, maxId);
				}
			} catch (Exception e) {
				error = e.getMessage();
				e.printStackTrace();
			}
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			if ("OK".equals(result)) {
				if (list != null) {
					if (list.size() < 20) {
						listView.removeFooterView(foot);
					} else if (listView.getFooterViewsCount() == 0) {
						listView.addFooterView(foot);
					}
					if (maxId == null) {
						statusList.clear();

					}
					statusList.addAll(list);
					adapter.notifyDataSetChanged();

				} else {
					Toast.makeText(SearchListActivity.this, R.string.service_no_response, Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(SearchListActivity.this, result, Toast.LENGTH_SHORT).show();
			}
			if (maxId == null) {
				listView.onRefreshComplete();
			}
			footProgressBar.setVisibility(View.INVISIBLE);
			flag = true;
		}
	}
}
